package interface_layer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import processing_layer.Course;

import database_layer.Common;
import database_layer.QueryDispatcher;
import database_layer.UpdateDispatcher;

/**
 * This servlet handles the course removal in the web service. It is triggered
 * by one of the button options on the administrator panel
 */
public class RemoveCourse extends HttpServlet
{
	private static final long serialVersionUID = 1L;
       
    public RemoveCourse()
    {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String username = (String) request.getSession().getAttribute("username");
			String userType = (String) request.getSession().getAttribute("userType");
			
			if (null == username || null == userType)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			if (!userType.equals(Common.adminType))
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			String courseName = request.getParameter("courseToRemove");
			
			if (null == courseName)
			{
				ErrorHandler.parseForErrors(Common.BAD_PARAMETERS, response, null);
				return;
			}
			
			/* First, making sure the this admin is the one that created the course! */
			Course courseDetails = QueryDispatcher.getCourseDetails(courseName);
				
			if (null == courseDetails)
			{
				ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
				return;
			}
				
			if (null == courseDetails.name)
			{
				ErrorHandler.parseForErrors(Common.ENTRY_DOESNT_EXIST, response, null);
				return;
			}
				
			if (!username.equals(courseDetails.courseCreator))
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
				
			int returnValue = UpdateDispatcher.removeCourse(courseName);
			ErrorHandler.parseForErrors(returnValue, response, "allCourses.jsp");
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}
}
